package com.clhbolg.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clhbolg.domain.UserRole;
import com.clhbolg.domain.bo.UserRoleBo;
import com.clhbolg.domain.vo.UserRoleVo;
import com.clhbolg.mapper.UserRoleMapper;
import com.clhbolg.model.dto.UserRoleDTO;
import com.clhbolg.model.vo.request.UserDisableVO;
import com.clhbolg.model.vo.request.UserRoleVO;
import com.clhbolg.service.IUserRoleService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author cailinhu
 * @date 2023-02-08
 */
@RequiredArgsConstructor
@Service
public class UserRoleServiceImpl implements IUserRoleService {

    private final UserRoleMapper baseMapper;

    @Autowired
    private ISysRoleService iSysRoleService;
    @Resource
    private  SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private  ISysUserService userService;
    /**
     * 查询【请填写功能名称】
     */
    @Override
    public UserRoleVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @Override
    public TableDataInfo<UserRoleVo> queryPageList(UserRoleBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<UserRole> lqw = buildQueryWrapper(bo);
        Page<UserRoleVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @Override
    public List<UserRoleVo> queryList(UserRoleBo bo) {
        LambdaQueryWrapper<UserRole> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<UserRole> buildQueryWrapper(UserRoleBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<UserRole> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, UserRole::getUserId, bo.getUserId());
        lqw.eq(bo.getRoleId() != null, UserRole::getRoleId, bo.getRoleId());
        return lqw;
    }

    /**
     * 新增【请填写功能名称】
     */
    @Override
    public Boolean insertByBo(UserRoleBo bo) {
        UserRole add = BeanUtil.toBean(bo, UserRole.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改【请填写功能名称】
     */
    @Override
    public Boolean updateByBo(UserRoleBo bo) {
        UserRole update = BeanUtil.toBean(bo, UserRole.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(UserRole entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除【请填写功能名称】
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<UserRoleDTO> queryRoles() {
        List<SysRole> sysRoles = iSysRoleService.selectRoleAll();
        List<UserRoleDTO> collect = sysRoles.stream().map(e -> {
            UserRoleDTO build = UserRoleDTO.builder().roleName(e.getRoleName()).id(e.getRoleId()).build();
            return build;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    @Transactional
    public void updateUserRole(UserRoleVO vo) {
        Long userId = vo.getId();
        // 删除用户与角色关联
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId));
        // 新增用户与角色管理
        insertUserRole(vo);
    }

    private void insertUserRole(UserRoleVO vo) {
        List<Long> roleIds = vo.getRoleIds();
        if (ArrayUtil.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<>(roleIds.size());
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(vo.getId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            sysUserRoleMapper.insertBatch(list);
        }
    }

    @Override
    public void updateUserDisable(UserDisableVO userDisableVO) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userDisableVO.getId());
        sysUser.setStatus(userDisableVO.getIsDisable().toString());
        userService.updateUserStatus(sysUser);
    }
}
